package indi.mozping.client;

import indi.mozping.handler.RedisClientInitializer;
import io.netty.bootstrap.Bootstrap;
import io.netty.channel.Channel;
import io.netty.channel.ChannelFuture;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.util.concurrent.GenericFutureListener;

import java.io.BufferedReader;
import java.io.InputStreamReader;

/**
 * @author by mozping
 * @Classname EchoClient
 * @Description RedisClient客户端，需要做的是：
 * 1.连接服务器
 * 2.发送信息
 * 3.发送的每个信息，等待和接收从服务器返回的同样的信息
 * 4.关闭连接
 * 这里面的写法和服务端很相似
 * @Date 2019/9/11 19:25
 */
public class RedisClient {

    private static final String HOST = "192.168.13.53";
    private static final int PORT = 6379;

    private static void start() throws Exception {
        EventLoopGroup group = new NioEventLoopGroup();
        try {
            //1.创建 Bootstrap
            Bootstrap b = new Bootstrap();
            //2.指定 EventLoopGroup 来处理客户端事件。由于我们使用 NIO 传输，所以用到了 NioEventLoopGroup 的实现
            b.group(group)
                    //3.使用的 channel 类型是一个用于 NIO 传输
                    .channel(NioSocketChannel.class)
                    .handler(new RedisClientInitializer());

            Channel channel = b.connect(HOST, PORT).sync().channel();
            System.out.println("Connected to host : " + HOST + ", port : " + PORT);
            System.out.println("Type redis's command to communicate with redis-server or type 'quit' to shutdown ");
            BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
            ChannelFuture f = null;

            for (; ; ) {
                String s = in.readLine();
                if ("quit".equalsIgnoreCase(s)) {
                    break;
                }
                System.out.print(">");
                f = channel.writeAndFlush(s);
                f.addListener(new GenericFutureListener<ChannelFuture>() {
                    public void operationComplete(ChannelFuture future) throws Exception {
                        if (!future.isSuccess()) {
                            System.err.print("write failed: ");
                            future.cause().printStackTrace(System.err);
                        }
                    }
                });
            }
            if (f != null) {
                f.sync();
            }
            System.out.println("bye...");

        } finally {
            //关闭线程池和释放所有资源
            group.shutdownGracefully().sync();
        }
    }

    public static void main(String[] args) throws Exception {
        RedisClient.start();
    }
}